// @flow
import React from 'react'
import { Form, Input, Button, DatePicker, message, Select } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './CustomerForm.css'
const FormItem = Form.Item
const Option = Select.Option
type Props = {
  form: Object,
  onChange: Function,
  customerId: string
}

type State = {
  loading: boolean,
  customerEventType: Array<Object>
}

class CustomerForm extends React.Component {
  props: Props
  state: State
  handleOk: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      loading: false,
      customerEventType: []
    }
    this.handleOk = this.handleOk.bind(this)
  }

  componentWillMount () {
    universalFetch(`${__SERVICE_API__}sys/dicts?type=customerEventType`)
    .then(res => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        customerEventType: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  handleOk (e) {
    const { customerId } = this.props
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const formValue = {
          ...values,
          'customerId': customerId,
          'startTime': values['startTime'].format(),
          'endTime': values['endTime'].format()
        }
        universalFetch(`${__SERVICE_API__}device/events/customers`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(formValue)
        })
          .then((res) => res.json())
          .then((json) => {
            if (json.code !== 200000) {
              throw new Error(JSON.stringify({ code: json.code, message: json.message }))
            }
            this.setState({ loading: false })
            if (json.code === 200000) {
              message.success('事件添加成功')
              this.props.onChange()
            } else {
              message.error('事件添加失败，请重新添加')
            }
          })
          .catch((error) => {
            handleFetchError(error)
            console.error(error)
          })
      }
    })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { customerEventType } = this.state
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    }
    return (
      <Form onSubmit={this.handleOk} className={styles['main']}>
        <FormItem
          {...formItemLayout}
          label='事件名称'>
          {getFieldDecorator('eventName', {
            rules: [{ required: true, message: '请输入用户名!', whitespace: true }]
          })(
            <Input type='text' placeholder='请填写事件名称' />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label='事件类型'>
          {getFieldDecorator('eventType', {
            rules: [{ required: true, message: '请输入用户名!' }]
          })(
            <Select showSearch
              filterOption={(input, option) => {
                return option.props.children.indexOf(input) >= 0
              }} placeholder='请选择事件类型'>
              {
                customerEventType.map((d, i) => {
                  return <Option key={i} value={d.value}>
                    {d.label}
                  </Option>
                })
              }
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label='开始时间'>
          {getFieldDecorator('startTime')(
            <DatePicker showTime format='YYYY-MM-DD HH:mm:ss' />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label='结束时间'>
          {getFieldDecorator('endTime')(
            <DatePicker showTime format='YYYY-MM-DD HH:mm:ss' />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label='处理方法'>
          {getFieldDecorator('dealMethod')(
            <Input type='text' placeholder='请填写处理方法' />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label='事件描述'>
          {getFieldDecorator('detail')(
            <Input type='textarea' placeholder='请填写事件描述' />
          )}
        </FormItem>
        <p className={styles['buttonCon']}>
          <Button type='primary' htmlType='submit' loading={this.state.loading}>
            提 交
          </Button>
        </p>
      </Form>
    )
  }
}

export default Form.create()(CustomerForm)
